import React from 'react';

import CommentInput from './components/CommentInput';
import CommentListItem from './components/CommentListItem';
import NoComment from './components/NoComment';

export default class App extends React.Component {
  constructor() {
    super();

    this.state = {
      commentList: [
        // {
        //   id: 1,
        //   name: 'jack',
        //   text: '哈哈，沙发！！！'
        // }
      ],
      userName: '',
      userContent: ''
    };
  }

  //关联输入框文本内容
  handleForm(e) {
    //获取子组件传递过来的e
    const { name, value } = e.target;

    //name -> userName/userContent
    //根据name设置对应state
    this.setState({
      [name]: value
    });
  }

  //发表评论
  handleFormSubmit() {
    const { userName, userContent, commentList } = this.state;

    //获取评论人和评论内容
    const commentItem = {
      id: new Date().getTime(),
      name: userName,
      text: userContent
    };

    //把拼接好的新的对象放到数组前面
    const newList = [commentItem, ...commentList];

    if (userName.length !== 0 && userContent.length !== 0) {
      //添加进评论列表数组里
      this.setState({ commentList: newList });

      //清空文本框内容
      this.setState({
        userName: '',
        userContent: ''
      });
    } else {
      alert('请填写评论人和评论内容！');
      return;
    }
  }

  render() {
    const { commentList, userName, userContent } = this.state;

    return (
      <div className="app" style={{ border: '1px solid', width: '300px' }}>
        <CommentInput
          userName={userName}
          userContent={userContent}
          handleForm={this.handleForm.bind(this)}
          handleFormSubmit={this.handleFormSubmit.bind(this)}
        />
        <br />

        {commentList && commentList.length > 0 ? (
          <CommentListItem commentList={commentList} />
        ) : (
          <NoComment />
        )}
      </div>
    );
  }
}
